package com.browsesoft.resource;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.Tools;
import com.browsesoft.baseadapter.HTMLBasicTableModel;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.noshow.NoShow;
import com.browsesoft.oa.MoreDelete;
import com.browsesoft.user.User;

/**
 * 资源表格model(OA后台使用)
 */
public class ResourceBasicTableModel extends HTMLBasicTableModel {
	/**
	 * 父资源ID
	 */
	private String parentID = null;

	/**
	 * 所有资源列表
	 */
	private LinkedList resources = null;

	/**
	 * 所属系统名::如果是GI系统，根据用户选择可以批量删除，其他系统不可以
	 */
	protected String systemName = null;

	/**
	 * 批量删除
	 */
	protected LinkedList checkChange = new LinkedList();

	/**
	 * 基本组件
	 */
	private HTMLBasicComponent component;

	/**
	 * 所要移动至的目的资源节点
	 */
	private Resource destinationResource = null;

	/**
	 * 不显示设置器
	 */
	private Map nowShowMachines = new HashMap();;

	/**
	 * 初始化
	 * 
	 * @param request
	 *            客户端请求
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		// 得到父资源ID
		this.parentID = request.getParameter("point");
		this.loginUser = (User) request.getSession().getAttribute("loginUser");
		// 如果有设置不显示配置
		gatherNoShowMachines();
	}

	/**
	 * 收集不显示设置器
	 */
	private void gatherNoShowMachines() {
		try {
			NodeList list = this.component.getPage().getElement()
					.getElementsByTagName("noshow");
			for (int i = 0; i < list.getLength(); i++) {
				Element elem = (Element) list.item(i);
				String className = elem.getAttribute("classname");
				NoShow show = (NoShow) Class.forName(className).newInstance();
				this.nowShowMachines.put(show, elem);
			}
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 得到列数
	 * 
	 * @return 列数
	 */
	public int getColumnCount() {
		return 9;
	}

	/**
	 * 得到列的名称
	 * 
	 * @param index
	 *            列号
	 * @return 列的名称
	 */
	public String getColumnName(int index) {
		// 如果列数等于1
		if (index == 1) {
			return getShowName();
		} else {
			return "";
		}
	}

	private String getShowName() {
		if (this.component.getElement().hasAttribute("en")) {
			return "Resource Name";
		} else {
			return "资源名称";
		}
	}

	public String getColumnEname(int index) {
		if (index == 1) {
			return "name";
		} else {
			return "";
		}
	}

	public Object getDatas() {
		return resources;
	}

	/**
	 * 得到行数
	 * 
	 * @return 行数
	 */
	public int getRowCount() {
		return resources.size();
	}

	/**
	 * 上移资源
	 */
	public void up(HttpServletRequest request) {
		try {
			// 取得要移动的对象
			String id = request.getParameter("id");
			BasicResource res = (BasicResource) EntityManager.getInstance()
					.getObject(id);
			// 如果在顶部
			LinkedList list = Tools.iteratorToList(res.getParent()
					.getChildren());
			int pos = list.indexOf(res);
			if (pos == 0) {
				// 不做
				return;
			}
			// 与上一个对象换位
			BasicResource upRes = (BasicResource) list.get(pos - 1);
			BasicResource parent = (BasicResource) upRes.getParent();
			parent.switchPostion(upRes, res);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * 下移资源
	 */
	public void down(HttpServletRequest request) {
		try {
			// 取得要移动的对象
			String id = request.getParameter("id");
			BasicResource res = (BasicResource) EntityManager.getInstance()
					.getObject(id);
			// 如果在底部
			LinkedList list = Tools.iteratorToList(res.getParent()
					.getChildren());
			int pos = list.indexOf(res);
			if (pos == list.size() - 1) {
				// 不做
				return;
			}
			// 与下一个对象换位
			BasicResource downRes = (BasicResource) list.get(pos + 1);
			BasicResource parent = (BasicResource) downRes.getParent();
			parent.switchPostion(downRes, res);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	/**
	 * 处理用户请求
	 * 
	 * @param request
	 *            客户端请求
	 * @param response
	 *            响应
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String action = request.getParameter("action");
		// 如果是上移资源
		if (action != null && action.equals("up")) {
			// 上移资源
			up(request);
		}
		// 如果是下移资源
		else if (action != null && action.equals("down")) {
			// 下移资源
			down(request);
		}
		// 得到系统名
		systemName = this.component.getElement().getAttribute("systemname");
		if (systemName != null && systemName.equals("browseGI")) {
			// 批量删除
			this.deleteResource(request, this.component);
			// 多资源移动
			if (this.destinationResource != null) {
				this.moveMultiResouce(request, this.component);
			}
		}
		// 如果没有点击资源树
		if (this.parentID == null) {
			resources = Tools.iteratorToList(EntityManager.getInstance()
					.getRoot().getChildren());
		} else {
			// 根据参数取得资源
			Resource resource = (Resource) EntityManager.getInstance()
					.getObject(this.parentID);
			if (resource == null) {
				return;
			}
			// 取得资源的所有子
			resources = Tools.iteratorToList(resource.getChildren());
			// 保存有子资源的资源名称和ID
			String resourceName = "";
			for (int i = 0; i < resources.size(); i++) {
				Resource re = (Resource) resources.get(i);
				Iterator list = re.getChildren();
				if (list.hasNext()) {
					String name = (String) re.getAttributes().get("name");
					String resourceID = re.getID();
					resourceName += name + "_" + resourceID + ",";
				}
			}
			resourceName += "资源";
			LinkedList list = (LinkedList) ExtendElement.findElements(
					this.component.getPage().getElement(), "resourcename",
					"resourcename");
			if (list.size() > 0) {
				Element e = (Element) list.get(0);
				e.setAttribute("value", resourceName);
			}
		}
		   //不显示过滤
		this.resources = (LinkedList) filterNoShow();
	}

	public void deleteResource(HttpServletRequest request,
			HTMLBasicComponent com) throws Exception {
		// 取得是否真正提交
		String action = request.getParameter("action");
		// 取得本次Check框的变化结果
		String re = request.getParameter("resultdarpent" + "_" + com.getName());
		// 对于每一个变化了的Check框
		LinkedList v = Tools.stringToLinkedList(re);
		for (int i = 0; i < v.size(); i++) {
			// 如果Check框上次已在变化集合中
			if (this.checkChange.contains(v.get(i))) {
				// 从变化集合中删除
				this.checkChange.remove(v.get(i));
			}
			// 否则
			else {
				// 添加该变化
				this.checkChange.add(v.get(i));
			}
		}
		// 如果真正提交，且有变化内容
		if (action != null && checkChange.size() > 0
				&& action.equals("deleteselected")) {
			// 删除所选择的实体
			MoreDelete.getinstance().deleteSelectedResource(checkChange,
					this.loginUser, com);
			checkChange.clear();
		}
	}

	/**
	 * 得到类型
	 * 
	 * @param col
	 *            列数
	 * @return 类型
	 */
	public String getType(int col) {
		String[] types = { "space", "checkbox", "image", "td", "up", "down",
				"modify", "delete", "space" };
		return types[col];
	}

	/**
	 * 替换link元素onclick属性中#id#部分为实体id号
	 */
	private void replaceID(Element td, BasicResource resource) {
		// 如果有link元素
		LinkedList list = ExtendElement.findElements(td, "type", "link");
		if (list.size() > 0) {
			// 替换link元素中的id号
			Element e = (Element) list.get(0);
			String str = e.getAttribute("onclick");
			str = str.replaceAll("#id#", resource.getID());
			e.setAttribute("onclick", str);
		}
	}

	/**
	 * 修改单元值
	 * 
	 * @param td
	 *            元素
	 * @param doc
	 *            文档
	 * @param row
	 *            行数
	 * @param col
	 *            列数
	 */
	public void modifyCellValue(Element td, Document doc, int row, int col) {
		// 根据行数取得资源
		Resource resource = (Resource) resources.get(row);
		// 替换onclick中的#id#为对象id号
		this.replaceID(td, (BasicResource) resource);
		// 如果是第1列
		if (col == 1) {
			LinkedList ls = ExtendElement.findElements(td, "type", "checkbox");
			if (ls.size() > 0) {
				// 替换流程id号
				Element e = (Element) ls.get(0);
				e.setAttribute("name", resource.getID());
				String onclick = e.getAttribute("onclick");
				onclick = onclick.replaceAll("result", "resultdarpent_"
						+ this.component.getName());
				e.setAttribute("onclick", onclick);
			}
		}
		// 否则,如果是第2列
		else if (col == 2) {
			Element image = (Element) ExtendElement.findElements(td, "type",
					"image").get(0);
			String icon = (String) resource.getAttributes().get("f_icon");
			String src = image.getAttribute("src");
			if (icon != null && !icon.equals("")) {
				src = src.replaceAll("fc_default", icon);
				image.setAttribute("src", src);
			}
		}
		// 否则,如果是第3列
		else if (col == 3) {
			String resourceName = (String) resource.getAttributes().get("name");
			// 如果列数等于0替换了列元素
			ExtendElement.replaceElementContext(td, doc
					.createTextNode(resourceName));
		}
		// 否则,如果是第4列
		else if (col == 4) {
		}
		// 否则,如果是第5列
		else if (col == 5) {
		}
		// 否则,如果是第6列
		else if (col == 6) {
			Element e = (Element) ExtendElement
					.findElements(td, "type", "link").get(0);
			String str = e.getAttribute("onclick");
			str = str.replaceAll("templatename=", "templatename="
					+ resource.getTemplateName());
			str = str.replaceAll("id=", "id=" + resource.getID());
			e.setAttribute("onclick", str);
		}
		// 否则,如果是第7列
		else if (col == 7) {
			LinkedList ls = ExtendElement.findElements(td, "type", "link");
			if (ls.size() > 0) {
				Element e = (Element) ls.get(0);
				// 取得属性
				String str = e.getAttribute("onclick");
				str = str.replaceAll("id=", "id=" + resource.getID());
				e.setAttribute("onclick", str);
			}
			
		}
		
      
	}
	
	/**
	 * 设置不显示
	 */
	private List filterNoShow()
	{
		List result = new LinkedList();
		result.addAll(this.resources);
		Iterator iter = this.nowShowMachines.keySet().iterator();
		while(iter.hasNext())
		{
			NoShow show = (NoShow)iter.next();
			Element elem  = (Element) this.nowShowMachines.get(show);
			result = show.filterShow(elem,result,this.component);
		}
		return result;
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	/**
	 * 更新页面元素
	 * 
	 * @param c
	 *            组件
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
		// 如果父id不为空
		if (this.parentID != null && !this.parentID.equals("")) {
			LinkedList nl = ExtendElement.findElements(c.getElement(), "name",
					"functionlink");
			Resource f = (Resource) EntityManager.getInstance().getObject(
					this.parentID);
			if (nl.size() > 0) {
				Element functionlink = (Element) nl.get(0);
				functionlink.setAttribute("value", (String) f.getAttributes()
						.get("link"));
			}
		}
	}

	/**
	 * 设置条件
	 * 
	 * @param condition
	 *            条件
	 */
	public void setCondition(String condition) {
	}

	/**
	 * 设置目的节点资源
	 */
	public void setDestinationResource(Resource r) {
		this.destinationResource = r;
	}

	/**
	 * 移动多个资源到移动的节点上
	 */
	public void moveMultiResouce(HttpServletRequest request,
			HTMLBasicComponent com) throws Exception {
		// 如果需要移动的目的资源不为空
		Iterator iter = checkChange.iterator();
		// 对于每一个实体
		while (iter.hasNext()) {
			String id = (String) iter.next();
			BasicResource entity = (BasicResource) EntityManager.getInstance()
					.getObject(id);
			// 如果不为空
			if (entity != null) {
				// 移动
				Resource parent = entity.getParent();
				// 从parent中移走要移的功能
				parent.removeChild(entity);
				// 在fun下面添加
				destinationResource.addChild(entity);
				// 调用数据库更新
				entity.getAttributes().put("parentid",
						destinationResource.getID());
				entity.update();
				// 移动资源得成功提示
				this.component.getPage().showMessage(
						"alert('移动成功！');window.close();");
			}
		}
		// 状态恢复
		destinationResource = null;
	}
}